import { PipeTransform, Injectable, BadRequestException } from '@nestjs/common';
import { ZodSchema } from 'zod';

@Injectable()
export class ZodValidationPipe implements PipeTransform {
  constructor(private schema: ZodSchema) {}

  transform(value: any) {
    try {
      return this.schema.parse(value);
    } catch (error) {
      // 格式化Zod错误信息
      const zodError = error as any;
      const formattedErrors = zodError.issues?.map((err: any) => ({
        path: err.path.join('.'),
        message: err.message,
      }));
      throw new BadRequestException({
        message: '验证失败',
        errors: formattedErrors || zodError.message,
      });
    }
  }
}